const slime = @options("slime") || {};

try {

    const JSONRPCClient = require("../../../jsonrpc/library/jsonrpc-client.js");
    const url   = require("url");
    
    var client;
    if (slime && slime.rootURL) {
        client = new JSONRPCClient(slime);
    }
    
    module.exports = function (lab) {
        return {
            @uploadFile: function(file) {
                if (!@.fs.exists(file)) {
                    throw @lab.errors.object_not_found;
                }
                var session = @.async.env("session");
    
                if (slime && slime.rootURL) {
    
                    return @.async(function () {
                        
                        if (session && session.id) {
                            this.next(new JSONRPCClient(@.merge.simple(slime,{
                                mewSID : session.id
                            })));
                        } else {
                            this.next(client);
                        }
    
                    }).then(function (client) {
    
                        this.pool.jsonrpc = client;
                        client.call("slime@core.requestUploadToken",[],this.test);
    
                    }).then(function (uploadToken) {
    
                        var uploadURL = slime.uploadURL;
    
                        if (!uploadURL) {
                            var {protocol, host} = url.parse(slime.rootURL);
                            uploadURL = protocol + "//" + host + "/slime/fileupload";
                        }
    
                        this.pool.jsonrpc.routeTable['*'].client.multipartRequest(uploadURL, {
                            form: {
                                files: {
                                    file: {
                                        data: @.fs.readFile.stream(file),
                                        filename: @.fs.filename(file),
                                        contentType: "application/octet-stream"
                                    }
                                },
                                fields  : {
                                    id : uploadToken,
                                }
                            },
                            dataType: "json",
                            onSuccess: (result) => {
                                if (result.fileNames.length == 1){
                                    this.next(result.fileURLs[result.fileNames[0]] || result.filePaths[result.fileNames[0]]);
                                } else {
                                    throw new Error("Upload error");
                                }
                            },
                            onError: this.reject
                        })
    
                    })
                } else if (lab.slime) {
                    return lab.slime.core.@sendLocalFileToUploadPath({
                        member_id : session && session.currentMember ? session.currentMember.id : undefined ,
                        uid : session && session.currentUser ? session.currentUser.id : undefined , 
                        filePath : file
                    }).then(function ({filePath, fileName, fileURL}) {
                        this.next(fileURL ? fileURL : filePath);
                    });
                } else {
                    throw @lab.errors.not_support;
                }
    
            }
        }    
    }
} catch (ex){
    module.exports = function (lab) {
        return {
            @uploadFile: function(file) {
                throw @lab.errors.not_support;
            }
        }
    }
}
